package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.TravelComment;
import cn.wolfcode.wolf2w.query.TravelCommentQuery;
import cn.wolfcode.wolf2w.repository.TravelCommentRepository;
import cn.wolfcode.wolf2w.service.ITravelCommentService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
/**
* 游记评论服务接口实现
*/
@Service
//@Transactional  现在写不能事务, 需要讲完复制集才能使用事务
public class TravelCommentServiceImpl implements ITravelCommentService {

    @Autowired
    private TravelCommentRepository repsitory;

    @Autowired
    private MongoTemplate template;



    @Override
    public void save(TravelComment travelComment) {
        travelComment.setId(null);
        travelComment.setCreateTime(new Date());
        //维护关联评论；如果评论的是评论，需要引入上层评论
        //获取关联评论的id
        String refId = travelComment.getRefComment().getId();
        if (StringUtils.hasLength(refId)){
            //评论的是评论，需要引入上层评论
            //获取上层评论
            TravelComment travelComment1 = this.get(refId);
            travelComment.setType(TravelComment.TRAVLE_COMMENT_TYPE);
            travelComment.setRefComment(travelComment1);
        }else {
            travelComment.setType(TravelComment.TRAVLE_COMMENT_TYPE_COMMENT);
        }
        repsitory.save(travelComment);
    }

    @Override
    public void update(TravelComment travelComment) {
        repsitory.save(travelComment);
    }

    @Override
    public void delete(String id) {
        repsitory.deleteById(id);
    }

    @Override
    public TravelComment get(String id) {
        return repsitory.findById(id).orElse(null);
    }

    @Override
    public List<TravelComment> list() {
        return repsitory.findAll();
    }

    @Override
    public List<TravelComment> queryByTravelId(String travelId) {

        return repsitory.findByTravelId(travelId);
    }

    @Override
    public Page<TravelComment> query(TravelCommentQuery qo) {
        Query query = new Query();
        Pageable pageable = PageRequest.of(qo.getCurrentPage()- 1,qo.getPageSize(), Sort.Direction.ASC, "_id");
        return DBHelper.query(template,pageable, query,TravelComment.class, qo);
    }

    @Override
    public void saveOrUpdate(TravelComment travelComment) {
        if(StringUtils.hasLength(travelComment.getId())){
            //update
            this.update(travelComment);
        }else{
            //save
            this.save(travelComment);
        }
    }
}
